package osgi.classloader;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;

public class ClassLoaderService implements IClassLoaderService {

	public static ClassLoader classLoader;//OSGI外部的类加载器
	public static BundleContext bundleContext;

	public ClassLoader getClassLoader() {
		return classLoader;
	}

	public void setClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
		
		// 测试用：调用osgi外的方法
		Map paraMap = new HashMap();
		paraMap.put("component", "kindeditor");
		OutServiceFactory.invokeOutService(paraMap, this.classLoader);
		
	}
	
	public Object invokeOSGI(Map paraMap) {		
		System.out.println("&quot;调用osgi里的方法&quot;");
		String outPara = (String)paraMap.get("outPara");
		System.out.println("外部传过来的参数： " + outPara);
		Map map = new HashMap();
		map.put("ret", "&quot返回值&quot");
		
		String stopName = (String)paraMap.get("stop");
		if(stopName != null) {
			Bundle[] bundles = bundleContext.getBundles();
			for(int i = 0;i<bundles.length;i++) {
				Bundle bundle = bundles[i];
				System.out.println("bundleName = " + bundle.getSymbolicName());
				if(stopName.equals(bundle.getSymbolicName())) {
					try {
						bundle.stop();
					} catch (BundleException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				}
			}
		}
		
		String method = (String)paraMap.get("method");
		if("getBundles".equals(method)) {
			return bundleContext.getBundles();
		} else if("getBundleContext".equals(method)) {
			return bundleContext;
		}
				
		return map;
	}

}
